package com.xufx.thread.liaoxuefeng.thread5_syncThread;

/**
 * Created by xufx on 2021/12/28 12:42
 * 1. 加锁和解锁中间的区域被称之为临界区，任何时候进入临界区最多只能有一个线程执行
 * 2. synchronized会降低程序的性能
 * 3. synchronized总是能够正确的释放锁
 * 4. synchronized必须锁住的是同一个对象
 *
 * JVM规范定义了几种不需要枷锁的原子操作
 * 1. 基本类型赋值
 * 2. 引用类型赋值
 * 3. 64位的赋值不一定就是原子操作
 *
 * 每个线程都有各自的局部变量，互不影响，互相不可见，并不需要同步
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        AddThread addThread = new AddThread();
        DecThread decThread = new DecThread();
        addThread.start();
        decThread.start();
        addThread.join();
        decThread.join();
        System.out.println(Counter.count);
    }
}

class Counter{
    public static int count = 0;
    public static final Object lock = new Object();
}

class AddThread extends Thread{
    @Override
    public void run(){
        for (int i = 0; i < 10000; i ++){
            synchronized (Counter.lock){
            Counter.count += 1;}
        }
    }
}

class DecThread extends Thread{
    @Override
    public void run(){
        for (int i = 0; i < 10001; i++) {
            synchronized (Counter.lock){
                Counter.count -=1;
            }
        }
    }
}
